/*
	flad : Copyright 2010 Dale J Williams

	Licensed under the Apache License, Version 2.0 (the "License");
	you may not use this file except in compliance with the License.
	You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

	Unless required by applicable law or agreed to in writing, software
	distributed under the License is distributed on an "AS IS" BASIS,
	WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	See the License for the specific language governing permissions and
	limitations under the License.
*/
package lads.flad.display {
	
	import flash.display.MovieClip;
	import flash.display.Sprite;
	
	/**
	 * MovieAsset: Designed to wrap timeline animations, play by frame 
	 * loop labels.
	 * @author Dale J Williams
	 * @version 1.0
	 */
	public class MovieAsset extends Sprite {
		
		private var _asset				:MovieClip;
		private var _animLabel			:String;
		private var animComplete		:Function;
		private var _playing			:Boolean = true;
		private var _framesThisCycle	:int;
		
		public function MovieAsset(asset:MovieClip) {
			_asset = asset;
			addChild(asset);
		}
		
		public function update():void {	
			if (playing) {
				if (asset.currentFrame == asset.totalFrames)
					asset.gotoAndStop(1);
				else asset.nextFrame();
				_framesThisCycle++;
			}
			if (asset.currentLabel != animLabel) {
				if (animComplete != null) animComplete();
				else rewind();
				goToLabel(animLabel);
			}
		}

		public function playAnimation(animName:String, rewind:Boolean=false, animComplete:Function=null):void {
			animLabel = animName;
			playing = true;
			animComplete = animComplete;
			if (rewind) this.rewind();
		}
		
		public function stopAnimation(rewind:Boolean=false):void {
			playing = false;
			if (rewind) this.rewind();
		}
		
		public function isAtPosition(label:String, framesThisCycle:int):Boolean {
			return animLabel == label && framesThisCycle == framesThisCycle;
		}
		
		public function rewind():void {
			goToLabel(animLabel);
			_framesThisCycle = 0;
		}
		
		private function goToLabel(label:String):void {
			if (animLabel)
				asset.gotoAndStop(animLabel);
			else asset.gotoAndStop(1);
		}
		
		public function get animLabel():String { return _animLabel; }
		public function set animLabel(value:String):void {
			_animLabel = value;
		}
		
		public function get asset():MovieClip { return _asset; }
		
		public function get playing():Boolean { return _playing; }		
		public function set playing(value:Boolean):void {
			_playing = value;
		}
		
		public function get framesThisCycle():int { return _framesThisCycle; }		
		
	}

}